#coding=utf-8
'''
Created on 2017-06-20

@author: sandy
'''
import json
import logging
import zlib
import time
import clientfactory
import clientbuild


class Transaction(object):

    def __init__(self,transname,cfgname,content):
        self.transname = transname
        self.cfgname = cfgname
        self.content = content
        self.time = int(time.time())


class ConfigManager(object):
    
    def __init__(self):
        self.config = {}
        self.transaction = {}
        pass

    def addConfig(self,sid,filename):
        if self.config.get(filename,None) == None:
            self.config[filename] = []
        serverList = self.config[filename]
        if sid not in serverList:
            serverList.append(sid)
        
    
    def updateConfig(self,filename,content):
        serverList = self.config.get(filename,[])
        logging.info("updateConfig serverlist=%s",str(serverList))
        for i in serverList:
            client = clientfactory.instance.getClient(i)
            if client:
                zipcontent = zlib.compress(content)
                client.sendPacket(clientbuild.sendConfig(filename,zipcontent))
            else:
                logging.warn(u"sid = %d server is not exit",i)
        pass

    ########### Transaction 事务相关
    def addTransaction(self,transname,cfgname,content):
        trans = Transaction(transname,cfgname,content)
        l = []
        if transname in self.transaction.keys():
            l = self.transaction[transname]
            l.append(trans)
        else:
            l.append(trans)
            self.transaction[transname] = l


    def popTransaction(self,transname):
        return self.transaction.pop(transname)

    
    def checkTimeOutTrans(self):
        curtime = int(time.time())
        keys = []
        for transname,trans in self.transaction.items():
            timeout = []
            for tran in trans:
                if curtime - tran.time >= 600:
                    timeout.append(tran)
            for t in timeout:
                trans.remove(t)
            if len(trans) == 0:
                keys.append(transname)
        for key in keys:
            self.transaction.pop(key)
        

    


instance = ConfigManager()